package app.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import app.sys.data.comm.ApiCode;
import app.sys.data.comm.ApiResult;
import app.sys.data.entity.UserInfo;
import app.sys.data.form.UserUpdatePwdForm;
import app.sys.error.BizException;
import app.sys.mapper.UserInfoMapper;
import app.sys.utils.MyMD5Util;
import app.sys.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserInfoService extends ServiceImpl<UserInfoMapper, UserInfo> {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);

    public static final String RESET_PWD="123456";

    @Autowired
    private UserInfoMapper userInfoMapper;

    public Page<UserInfo> pageList(Page page, UserInfo param) {
        return userInfoMapper.pageList(page, param);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean save(UserInfo userInfo) {
        try {
            String encryptedPwd = MyMD5Util.getEncryptedPwd(RESET_PWD);
            userInfo.setPassword(encryptedPwd);
        } catch (Exception e) {
            logger.error("UserInfoService add error", e);
            throw new BizException("保存失败");
        }
        UserInfo user = this.getUserByUserCode(userInfo.getUserCode());
        if (user != null) {
            throw new BizException(ApiCode.EXIT_USER);
        }
        UserUtils.setInsetBaseData(userInfo);
        userInfoMapper.insert(userInfo);
        return true;
    }

    public boolean update(UserInfo userInfo) {
        userInfo.setPassword(null);
        updateById(userInfo);
        return true;
    }

    public boolean resetPwd(Long id) {
        try {
            UserInfo userInfo = this.getById(id);
            userInfo.setId(id);
            String encryptedPwd = MyMD5Util.getEncryptedPwd(RESET_PWD);
            userInfo.setPassword(encryptedPwd);
            updateById(userInfo);
        } catch (Exception e) {
            logger.error("UserInfoService resetPwd error", e);
            return false;
        }
        return true;
    }

    public ApiResult<UserInfo> doLogin(String userCode, String password) {
        //验证用户是否存在
        UserInfo user = this.getUserByUserCode(userCode);
        if (user == null) {
            return ApiResult.of(ApiCode.NOT_FOUND);
        }

        try {
            boolean loginFlag = MyMD5Util.validPassword(password, user.getPassword());
            if (!loginFlag) {
                return ApiResult.of(ApiCode.FAIL_PERMISSION.getStatus(), "密码校验失败");
            }
        } catch (Exception e) {
            return ApiResult.of(ApiCode.FAIL_PERMISSION);
        }

        return ApiResult.of(ApiCode.SUCCESS, user);
    }

    public UserInfo getUserByUserCode(String userCode) {
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(UserInfo::getUserCode, userCode).eq(UserInfo::getDelFlag, 1);
        return this.getOne(wrapper);
    }

    public ApiResult updatePassword(UserUpdatePwdForm form) {
        ApiResult<UserInfo> res = doLogin(form.getUserCode(), form.getPassword());
        //验证登录信息
        if (ApiCode.SUCCESS.getStatus() == res.getStatus()) {
            if (form.getNewPassword().equals(form.getConfirmPassword())) {
                String encryptedPwd = "";
                try {
                    encryptedPwd = MyMD5Util.getEncryptedPwd(form.getNewPassword());
                } catch (Exception e) {
                    log.error("updatePassword error", e);
                    return ApiResult.of(ApiCode.SUCCESS.getStatus(), "密碼解析error！");
                }
                UserInfo user = getUserByUserCode(form.getUserCode());
                UserInfo userInfo = new UserInfo();
                userInfo.setId(user.getId());
                userInfo.setUserCode(form.getUserCode());
                userInfo.setPassword(encryptedPwd);
                boolean updateById = updateById(userInfo);
                return ApiResult.of(ApiCode.SUCCESS.getStatus(), "密码修改成功！");
            } else {
                return ApiResult.of(ApiCode.FAIL.getStatus(), "兩次密碼不一致");
            }
        } else {
            return ApiResult.of(ApiCode.FAIL.getStatus(), "密码错误");
        }
    }

}
